<template>
  <view class="page-container">
    <scroll-view scroll-y>
      <view class="binding-container">
        <!-- 采购订单选择 -->
        <view class="search-section">
          <wd-picker
            :columns="selectInSockData"
            label="采购订单"
            v-model="queryCode"
            type="radio"
            filterable
            clearable
            @confirm="selectInSockChange"
            @clear="selectInSockClear"
          ></wd-picker>
        </view>

        <!-- 供应商信息 -->
        <view class="supplier-section">
          <wd-cell-group>
            <wd-cell title="供应商" :value="supplierName" />
          </wd-cell-group>
        </view>
        <!-- 原材料选择 -->
        <view class="materials-section">
          <wd-picker
            :columns="materialsData"
            label="原材料"
            v-model="selectedMaterial"
            type="radio"
            filterable
            clearable
            @confirm="selectMaterialChange"
          />
        </view>
        <!-- 称重操作区 -->
        <view class="weight-card">
          <wd-picker :columns="scalesData" label="请选择台秤" v-model="selectedScale" />
          <view class="weight-control">
            <view class="weight-input-container">
              <input
                type="number"
                class="weight-input"
                v-model="currentWeight"
                placeholder="请输入重量"
                placeholder-class="placeholder-style"
              />
            </view>
            <view class="button-group">
              <button class="btn-get" @tap="getWeight">获取重量</button>
              <button class="btn-confirm" @tap="confirmWeight">确认</button>
            </view>
          </view>
        </view>

        <scroll-view scroll-y style="max-height: 400rpx; overflow-y: auto">
          <view v-for="(record, index) in weightRecords" :key="record.code" class="weight-records">
            <wd-swipe-action>
              <view class="record-item">
                <view>
                  <wd-text :text="record.createTime" class="record-time"></wd-text>
                </view>
                <view>
                  <wd-text
                    :text="`${record.weight}${formatUnit(unit)}`"
                    class="record-weight"
                  ></wd-text>
                </view>
              </view>
              <template #right>
                <view class="delete-btn">
                  <wd-icon
                    name="delete"
                    size="22px"
                    color="#ff4d4f"
                    @tap="deleteRecord(index)"
                  ></wd-icon>
                </view>
              </template>
            </wd-swipe-action>
          </view>
        </scroll-view>

        <!-- <view class="weight-card">
          <wd-cell title="总重量" :value="`${currentWeight.toFixed(2)}kg`" />
        </view>
        <view class="weight-card">
          <wd-picker :columns="scalesData" label="请选择台秤" v-model="selectedScale" />

          <view class="weight-display">
            <view class="weight-actions">
              <wd-button type="primary" size="small" :round="false" @tap="getWeight">
                获取重量
              </wd-button>
              <wd-button type="success" size="small" :round="false" @tap="confirmWeight">
                确认
              </wd-button>
            </view>
          </view>
        </view>
        <view>
          <view v-for="(record, index) in weightRecords" :key="record.code" class="weight-records">
            <wd-swipe-action>
              <view class="record-item">
                <view>
                  <wd-text :text="record.createTime" class="record-time"></wd-text>
                </view>
                <view>
                  <wd-text :text="`${record.weight}kg`" class="record-weight"></wd-text>
                </view>
              </view>
              <template #right>
                <view class="delete-btn">
                  <wd-icon
                    name="delete"
                    size="22px"
                    color="#ff4d4f"
                    @tap="deleteRecord(index)"
                  ></wd-icon>
                </view>
              </template>
            </wd-swipe-action>
          </view>
        </view> -->

        <!-- 台秤选择 -->
        <!-- <view class="scale-section">
      <wd-picker :columns="scalesData" label="台秤" v-model="selectedScale" type="radio" />
    </view> -->

        <!-- 重量显示和操作 -->
        <!-- <view>
      <wd-cell-group class="weight-section">
        <wd-input v-model="currentWeight" label="重量">
          <template #suffix>
            <wd-button type="primary" @tap="getWeight" :round="false" size="small">
              获取重量
            </wd-button>
            <wd-button type="warning" @tap="confirmWeight" :round="false" size="small" class="ml-1">
              确认
            </wd-button>
            <view class="weight-count">称重次数：{{ weightRecords.length }}</view>
          </template>
        </wd-input>
      </wd-cell-group>
    </view> -->
        <!-- <wd-text :text="`称重次数：${weightRecords.length}`" size="small" class="right-text" /> -->
        <!-- 重量记录列表 -->
        <!-- <view class="weight-records">
      <wd-swipe-action>
        <view
          v-for="(record, index) in weightRecords"
          :key="index"
          :right="[{ text: '删除', type: 'danger' }]"
          @tap="deleteRecord(index)"
        >
          <wd-cell :title="'重量: ' + record.weight" :value="record.time" />
        </view>
      </wd-swipe-action>
    </view> -->

        <!-- 筐码输入 -->
        <view class="basket-code-section">
          <wd-cell-group>
            <wd-input v-model="basketCode" label="筐码" placeholder="请输入或扫描筐码">
              <!-- <template #suffix>
          <wd-button type="primary" @tap="bindBasketCode" :round="false" size="small">
            绑定筐码
          </wd-button>
        </template> -->
            </wd-input>
          </wd-cell-group>
        </view>

        <!-- 备注 -->
        <!-- <view class="remark-section">
    <wd-textarea v-model="remark" label="备注" placeholder="请输入备注信息" />
  </view> -->
      </view>
    </scroll-view>
    <!-- 提交按钮 -->
    <view class="bottom-buttons">
      <wd-row>
        <wd-col :span="24">
          <!-- <wd-button
            type="primary"
            block
            @tap="
              getBasketCode('S2503250000003;PRO0000046;土豆;15;kg;PUR20250325000000003;深圳海吉星')
            "
            :round="false"
          >
            测试
          </wd-button> -->
          <wd-button type="primary" block @tap="submitData" :round="false">完成绑定</wd-button>
        </wd-col>
      </wd-row>
    </view>
    <scanCode @scanSuccess="getBasketCode"></scanCode>
  </view>
</template>

<script lang="ts" setup>
import scanCode from '@/components/scanCode/scanCode.vue'
import goodsReceiptApi, { ScaleCode, WeightRecord } from '@/api/goodsReceipt'
import { ref, reactive } from 'vue'
import { useMessage, useToast } from 'wot-design-uni'
import { ScanPatternType } from '@/api/scanCode'
import { formatCurrentTime } from '@/utils/time'
import { formatUnit } from '@/utils/unit'
import myPicker from '@/components/selectPicker/myPicker.vue'
const message = useMessage()
const toast = useToast()
// 获取入库单
const selectInSockData = ref([])
const selectCompany = ref('')
const queryCode = ref('')
const queryParams = reactive({
  pageNum: 1,
  pageSize: 999,
  statusList: [4, 5],
})
const unit = ref('kg')

const selectMaterialChange = (val: any) => {
  console.log(val)
  unit.value = val.selectedItems.unit
}

const selectInSockChange = (val: any) => {
  console.log(val)

  const selected = selectInSockData.value.find((item) => item.value === val.value)
  console.log(selected)

  if (selected) {
    supplierName.value = selected.companyName
    // 获取该采购单对应的原材料列表
    getMaterialsList(selected.code)
  }
}
const selectInSockClear = () => {
  queryCode.value = ''
}
// 获取所有入库单
const getAllInSock = () => {
  // 这里写获取入库单的接口
  goodsReceiptApi.getPurchaseOrderList(queryParams).then((res: any) => {
    selectInSockData.value = res.data.list.map((item: any) => {
      return {
        label: item.code,
        value: item.code,
        companyName: item.companyName,
        code: item.code,
      }
    })
  })
}

// 新增的响应式数据
const supplierName = ref('')
const materialsData = ref([])
const selectedMaterial = ref('')
// 台秤列表
const scalesData = ref([
  { value: ScaleCode.SCALE_1, label: '1号台秤' },
  { value: ScaleCode.SCALE_2, label: '2号台秤' },
])
const selectedScale = ref<ScaleCode>()
const currentWeight = ref<string>('0.00')

const weightRecords = ref<WeightRecord[]>([])
const basketCode = ref('')
const weightData = ref<WeightRecord>({
  code: '',
  sourceCode: '',
  productName: '',
  productCode: '',
  weight: 0,
  createTime: '',
})
// 总重量
const totalWeight = computed(() => {
  return weightRecords.value.reduce((total, record) => total + Number(record.weight), 0).toFixed(2)
})
// // 打印筐码
// const printRecord = (code: string) => {
//   message
//     .prompt({
//       title: '是否确认打印筐码？',
//       inputValue: code,
//       inputPattern: /^[0-9]+(\.[0-9]{1,2})?$/,
//       inputPlaceholder: '请输入筐码',
//       confirmButtonText: '确认打印',
//       cancelButtonText: '取消',
//     })
//     .then((resp) => {
//       console.log(resp)
//       console.log(code, '打印标签')
//       toast.success(`打印成功,筐码${code}`)
//     })
//     .catch((error) => {
//       console.log(error)
//     })
// }

// 获取原材料列表
const getMaterialsList = (code: string) => {
  // TODO: 调用获取原材料列表接口
  goodsReceiptApi.getPurchaseOrderDetail(code).then((res: any) => {
    materialsData.value = res.data.map((item: any) => {
      return {
        label: item.productName,
        value: item.productCode,
        unit: item.unit,
      }
    })
  })
}

// 获取重量
const getWeight = async () => {
  if (!selectedScale.value) {
    return toast.error('请先选择台秤')
  }
  try {
    // TODO: 调用获取重量API
    const res = await goodsReceiptApi.getScaleInfo(
      selectedScale.value,
      queryCode.value,
      selectedMaterial.value,
    )
    console.log(res)
    if (res.data.createTime) currentWeight.value = res.data.weight.toString()
    // if (weightRecords.value.some((item) => item.createTime === res.data.createTime)) {
    //   return toast.error('该条重量记录已存在，请勿重复添加')
    // } else {
    //   currentWeight.value = res.data.weight.toString()
    //   // weightRecords.value.push(res.data)
    //   toast.success('获取重量成功')
    // }
  } catch (error) {
    console.log(error)
  }
}
// 确认按钮点击事件处理函数
// 确认重量
const confirmWeight = async () => {
  if (currentWeight.value === '0.00') {
    return toast.error('请先获取重量')
  }

  weightRecords.value.unshift({
    code: weightData.value.code,
    sourceCode: weightData.value.sourceCode,
    productName: weightData.value.productName,
    productCode: weightData.value.productCode,
    weight: Number(currentWeight.value),
    createTime: formatCurrentTime(),
  })
  currentWeight.value = '0.00'
  toast.success('添加称重记录成功')
}

// 删除重量记录
const deleteRecord = (index: number) => {
  weightRecords.value.splice(index, 1)
}

// 提交数据
const submitData = () => {
  console.log(totalWeight.value, basketCode.value, selectedMaterial.value)

  // TODO: 实现筐码绑定逻辑
  if (totalWeight.value === '0.00' || !basketCode.value || !selectedMaterial.value) {
    return toast.error('请完善信息后再进行提交操作')
  }
  goodsReceiptApi
    .bindBasket({
      parentCode: basketCode.value,
      productCode: selectedMaterial.value,
      qty: Number(totalWeight.value),
      sourceCategory: 1,
      sourceCode: queryCode.value,
    })
    .then((res: any) => {
      toast.success('绑定成功')
      // 清空页面数据
      // printRecord(basketCode.value)
      weightRecords.value = []
      basketCode.value = ''
      // selectedScale.value = undefined
      // selectedMaterial.value = ''
      // queryCode.value = ''
    })
}

const getBasketCode = async (code: string) => {
  // 可能扫描标签码，可能扫描筐码。扫描标签待出当前信息，扫描筐码给筐码赋值
  console.log(code)
  if (ScanPatternType.BASKET_CODE.test(code)) {
    // 扫描的是筐码

    //判断是否是空筐
    goodsReceiptApi.getBasketByCode(code).then((res: any) => {
      if (res.data) {
        goodsReceiptApi.getBasketRecordByCode(code).then((res: any) => {
          if (res.data?.productCode) {
            toast.error('该筐码已绑定，请勿重复绑定')
          } else {
            basketCode.value = code
          }
        })
      }
    })
  } else if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(code)) {
    // 扫描的是标签码，获取入库单详情
    const [basket, productCode, productName, qty, unit, purCode, suppInfoName] = code.split(';')
    await getMaterialsList(purCode)
    selectedMaterial.value = productCode
    queryCode.value = purCode
    supplierName.value = suppInfoName
    weightRecords.value.push({
      code: basket,
      sourceCode: queryCode.value,
      productName,
      productCode,
      weight: Number(qty),
      createTime: formatCurrentTime(),
    })
  } else {
    toast.error('请扫描标签码或筐码！')
  }
}

onLoad(() => {
  getAllInSock()
})
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
}
.binding-container {
  padding: 24rpx;
  margin-bottom: 120rpx;
}

.search-section,
.supplier-section,
.materials-section,
.scale-section,
.weight-section,
.weight-records,
.basket-code-section {
  margin-bottom: 30rpx;
}
.weight-card,
.record-card {
  margin-bottom: 20rpx;
  font-size: 28rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  .value {
    font-size: 24rpx;
    // color: $primary-color;
  }
}
.weight-control {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  margin-top: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  .weight-input-container {
    position: relative;
    flex: 1;
    margin-right: 60rpx;
    .weight-input {
      width: 100%;
      height: 80rpx;
      padding: 0 20rpx;

      font-size: 14px;
      color: #333;
      background-color: #f5f5f5;
      border-radius: 8rpx;
    }
    .weight-unit {
      position: absolute;
      top: 50%;
      right: 20rpx;
      font-size: 14px;
      color: #666;
      transform: translateY(-50%);
    }
  }
  .button-group {
    display: flex;
    gap: 20rpx;
    .btn-get {
      font-size: 14px;
      color: #fff;
      background-color: #4080ff;
    }
    .btn-confirm {
      font-size: 14px;
      color: #fff;
      background-color: #52c41a;
    }
  }
}
// 统一卡片样式
:deep(.wd-cell-group),
:deep(.wd-picker) {
  overflow: hidden;
  background-color: #ffffff;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
}

// 称重区域样式
.weight-section {
  display: flex;
  align-items: center;

  :deep(.wd-input.is-cell) {
    padding: 24rpx 32rpx;

    .wd-input__label {
      font-weight: 500;
      color: #303133;
    }

    .wd-input__suffix {
      display: flex;
      flex-wrap: wrap;
      gap: 16rpx;
      align-items: center;

      .wd-button {
        min-width: 140rpx;
        height: 70rpx;
        font-size: 28rpx;
      }
    }
  }
}

// 确认按钮样式增强
.ml-1 {
  margin-left: 16rpx;
}

// 称重次数样式
.weight-count {
  margin-top: 8rpx;
  margin-left: auto;
  font-size: 24rpx;
  color: #909399;
}

.weight-card,
.record-card {
  padding: 20rpx;

  margin-bottom: 20rpx;
  font-size: 28rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
  .value {
    font-size: 24rpx;
    color: #909399;
  }
}
.inspection {
  flex-shrink: 0;
  padding: 30rpx;
  margin-top: 20rpx;
  background-color: #ffffff;
  .stats {
    display: flex;
    justify-content: space-between;
    margin-bottom: 30rpx;
    .stat-item {
      text-align: center;
      .stat-label {
        font-size: 14px;
        color: #666666;
      }
      .stat-value {
        display: block;
        margin-top: 10rpx;
        font-size: 16px;
        font-weight: bold;
        color: #333333;
      }
      .editable-weight {
        display: flex;
        align-items: center;
        margin-top: 10rpx;
        .weight-input {
          width: 100rpx;
          height: 50rpx;
          padding: 0 10rpx;
          font-size: 16px;
          font-weight: bold;
          color: #333333;
          text-align: center;
          border: 1px solid #dddddd;
          border-radius: 6rpx;
        }
        .weight-unit {
          margin-left: 10rpx;
          font-size: 14px;
          color: #666666;
        }
      }
    }
  }
  .progress-bar {
    margin-bottom: 30rpx;
    .progress-text {
      margin-bottom: 10rpx;
      font-size: 14px;
      color: #666666;
    }
    .progress-track {
      height: 20rpx;
      overflow: hidden;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      .progress-fill {
        height: 100%;
        background-color: #3e7bfa;
        transition: width 0.3s ease;
      }
    }
  }
}

.weight-display {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 0 20rpx;
  .weight-text {
    display: flex;
    align-items: center;
    justify-content: center;
    .weight-value {
      font-size: 48rpx;
      font-weight: bold;
      color: #333333;
    }
  }
  .weight-actions {
    display: flex;
    justify-content: space-around;

    button {
      margin: 0 10rpx;
    }
  }
}
.weight-records {
  width: 100%;

  .record-item {
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 30rpx;

    background-color: #ffffff;
    border-radius: 10rpx;
    box-shadow: inset 0 0 10rpx rgba(0, 0, 0, 0.1);
    .record-time {
      font-size: 14px;
      color: #666666;
    }
    .record-weight {
      font-size: 16px;
      font-weight: bold;
      color: #333333;
    }
  }
  .delete-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100rpx;
    height: 100%;
  }
}
// 筐码输入区域
.basket-code-section {
  :deep(.wd-input.is-cell) {
    background-color: #fff;
    border-radius: 12rpx;

    .wd-input__inner {
      border-bottom: rgba(0, 0, 0, 0.2) 1px solid;
    }
  }
}

// 底部按钮区域
.bottom-buttons {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 9;
  padding: 24rpx 32rpx;
  background-color: #fff;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.08);

  :deep(.wd-button) {
    height: 90rpx;
    font-size: 32rpx;
    font-weight: 500;
    letter-spacing: 2rpx;
    border-radius: 8rpx;

    // 按钮按压效果
    transition: all 0.2s;
    &:active {
      opacity: 0.9;
      transform: scale(0.98);
    }
  }
}
</style>
